package org.jaaksi.demo.ptr.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

/**
 * 创建时间：2016年09月06日18:22 <br>
 * 作者：fuchaoyang <br>
 * 描述：重构的列表页基类，使用起来更方便，目前不处理多种type的，添加对局部刷新的支持
 */
public abstract class BaseSimpleAdapter<D, Holder> extends BaseListAdapter<D> {

  public BaseSimpleAdapter(Context context) {
    super(context);
  }

  @Override public View getView(int position, View convertView, ViewGroup parent) {
    Holder holder;
    D d = getItem(position);
    if (convertView == null) {
      convertView = mInflater.inflate(getLayoutId(), parent, false);
      holder = onCreateViewHolder(convertView);
      convertView.setTag(holder);
    } else {
      holder = (Holder) convertView.getTag();
    }
    onBindViewHolder(holder, d, position);

    return convertView;
  }

  public abstract int getLayoutId();

  /**
   * 创建Holder
   */
  public abstract Holder onCreateViewHolder(View convertView);

  /**
   * 绑定数据
   */
  public abstract void onBindViewHolder(Holder holder, D d, int position);

  /**
   * 局部刷新的方法，如果不指明header个数，这里只考虑listView,其余按0处理
   *
   * @param parent AdapterView
   * @param position 需要刷新的position,这里的position不包含header
   */
  public void updateItemUI(AdapterView parent, int position) {
    int headerCount = 0;
    if (parent instanceof ListView) {
      headerCount = ((ListView) parent).getHeaderViewsCount();
    }
    updateItemUI(parent, position, headerCount);
  }

  /**
   * 局部刷新的方法
   *
   * @param parent AdapterView
   * @param position 需要刷新的position,这里的position不包含header
   * @param headerCount header个数
   */
  public void updateItemUI(AdapterView parent, int position, int headerCount) {
    int realPosition = position + headerCount;
    int firstVisiblePosition = parent.getFirstVisiblePosition();
    int lastVisiblePosition = parent.getLastVisiblePosition();
    // 判断position是否可见，如果可见调用updateUI方法
    if (realPosition >= firstVisiblePosition && realPosition <= lastVisiblePosition) {
      View view = parent.getChildAt(realPosition - firstVisiblePosition);
      onBindViewHolder((Holder) view.getTag(), getItem(position), position);
    }
  }
}
